package com.usian.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.usian.common.BaseServiceImpl;
import com.usian.common.fastdfs.FastDFSClient;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmMaterialDto;
import com.usian.model.media.pojos.WmMaterial;
import com.usian.model.media.pojos.WmNewsMaterial;
import com.usian.utils.threadlocal.WmThreadLocalUtils;
import com.usian.wemedia.mapper.WmMaterialMapper;
import com.usian.wemedia.mapper.WmNewsMaterialMapper;
import com.usian.wemedia.service.WmMaterialService;
import com.usian.wemedia.service.WmUserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;

@Service
public class WmMaterialServiceImpl extends BaseServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
    @Autowired
    FastDFSClient fastDFSClient;
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Value("${fdfs.url}")
    private String fileServerUrl;

    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        //1.检查参数
        if (multipartFile == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.上传图片到fasfdfs
        String fileId = null;
        try {
            fileId = fastDFSClient.uploadFile(multipartFile);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }

        //3.保存素材数据到表中 wm_material

        Integer user = WmThreadLocalUtils.getUserId();

        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUrl(fileId);
        wmMaterial.setIsCollection((short) 0);
        wmMaterial.setUserId(user);
        wmMaterial.setType((short) 0);
        wmMaterial.setCreatedTime(new Date());
        save(wmMaterial);
        //拼接图片路径
        wmMaterial.setUrl(fileServerUrl + fileId);
        return ResponseResult.okResult(wmMaterial);
    }

    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        if (dto == null) return errorResult;
        Integer userId = WmThreadLocalUtils.getUserId();
        if (userId == null) return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "用户id不存在");
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmMaterial::getUserId, userId);
        if (dto.getIsCollection() != null && dto.getIsCollection() == 1) {
            wrapper.eq(WmMaterial::getIsCollection, 1);
        }
        wrapper.orderByDesc(WmMaterial::getCreatedTime);
        Page<WmMaterial> page = new Page<>(dto.page, dto.size);
        IPage<WmMaterial> iPage = page(page, wrapper);
        ResponseResult<List<WmMaterial>> result = new PageResponseResult(dto.page, dto.size, (int) iPage.getTotal());
        List<WmMaterial> list = iPage.getRecords();

        List<WmMaterial> collect = list.stream().map(wmMaterial -> {
            wmMaterial.setUrl(fileServerUrl + wmMaterial.getUrl());
            return wmMaterial;
        }).collect(Collectors.toList());


//        for (WmMaterial material : list) {
//            material.setUrl(fileServerUrl+material.getUrl());
//        }
//        list.forEach(b->b.setUrl(fileServerUrl+b.getUrl()));
//        list.forEach(new Consumer<WmMaterial>() {
//            @Override
//            public void accept(WmMaterial wmMaterial) {
//                wmMaterial.setUrl(fileServerUrl+wmMaterial.getUrl());
//            }
//        });
        result.setData(collect);
        return result;
    }

    @Override
    public ResponseResult delPicture(Integer id) {
        if (id == null) return errorResult;
        WmMaterial wmMaterial = getById(id);
        LambdaQueryWrapper<WmNewsMaterial> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmNewsMaterial::getMaterialId, id);
        Integer count = wmNewsMaterialMapper.selectCount(wrapper);
        if (count > 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "当前图片被引用");
        }
        try {
            fastDFSClient.delFile(wmMaterial.getUrl());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
        removeById(id);
        return sucResult;
    }

    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        if (id == null) return errorResult;
        update(Wrappers.<WmMaterial>lambdaUpdate().set(WmMaterial::getIsCollection, type).eq(WmMaterial::getId, id));
        return sucResult;
    }
}
